#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    opcuaclient = OPCUAClient::instance();
    connect(
        opcuaclient,
        SIGNAL(realValueChanged(const QString&, float)), // 信号
        this,
        SLOT(updateLabelValue(const QString&, float)), // 槽函数
        Qt::QueuedConnection // 跨线程安全连接（回调在子线程触发）
        );

    QTimer *timer = new QTimer(this);
    timer->setInterval(1000);
    timer->start();
    connect(timer, SIGNAL(timeout()), this, SLOT(connectOpcua()));
    connect(this,SIGNAL(newbi()),this,SLOT(startSub()));
}

MainWindow::~MainWindow()
{
    opcuaclient->unsubscribeAll();
    opcuaclient->disconnectServer();
    delete ui;
}

void MainWindow::connectOpcua()
{
    if (opcuaclient->connectServer() == false)
    {
        ui->label_3->setStyleSheet("QLabel { background-color : rgb(255, 0, 0); }");
    }
    else
    {
        ui->label_3->setStyleSheet("QLabel { background-color : rgb(0, 255, 0); }");
        emit newbi();
        disconnect(this,SIGNAL(newbi()),this,SLOT(startSub()));
    }
}

void MainWindow::updateLabelValue(const QString &alias, float value)
{
    ui->label_2->setText(QString("实时值：%1").arg(value, 0, 'f', 2));
}

void MainWindow::startSub()
{
    opcuaclient->subscribeReal("\"DB_HMI\".\"Command\".\"AxisX\".\"setPosition\"","test");
}

